package com.android.settings.audio.peq.peq.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.android.settings.audio.peq.peq.PeqAudioSettingUtils;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.android.settings.R;
import com.android.settings.audio.peq.peq.Band;
import com.android.settings.audio.peq.peq.ui.common.adapter.CommonAdapter;
import com.android.settings.audio.peq.peq.ui.dialog.CommanDialog;
import com.android.settings.audio.peq.peq.widget.PEQImportDialog;
import com.android.settings.audio.peq.qr.Constant;
import com.android.settings.audio.peq.qr.QrManager;
import com.android.settings.audio.peq.skin.SkinManager;
import com.android.settings.audio.peq.soundeffect.PluginDataManager;
import com.android.settings.audio.peq.soundeffect.ServerConfigList;
import com.android.settings.audio.peq.soundeffect.ServerConfigManager;
import com.android.settings.audio.peq.soundeffect.ServerConfigSave;
import com.android.settings.audio.peq.soundeffect.SoundEffectConfig;
import com.android.settings.audio.peq.soundeffect.SoundEffectManager;
import com.android.settings.audio.peq.user.Callback;
import com.android.settings.audio.peq.user.HibyUser;
import com.android.settings.audio.peq.user.UserManager;
import com.android.settings.audio.peq.util.BuildConfig;
import com.android.settings.audio.peq.util.CameraUtil;
import com.android.settings.audio.peq.util.FileUtil;
import com.android.settings.audio.peq.util.LogPlus;
import com.android.settings.audio.peq.util.NetWorkUtils;
import com.android.settings.audio.peq.util.ShareprefenceTool;
import com.android.settings.audio.peq.util.SmartPlayerApplication;
import com.android.settings.audio.peq.util.ToastTool;
import com.android.settings.audio.peq.util.Util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PeqActivityPresenter implements IPeq, MixerCallback.MixerMonitor {
    public Activity mActivity;
    IPeq.IPeqView peqActivity;


    public PeqActivityPresenter(Activity activity, IPeq.IPeqView mActivityInterface) {
        this.mActivity = activity;
        this.peqActivity = mActivityInterface;

        MixerCallback.getInstance().setMixerLinstener(this);
    }

    public void init() {
        try {
            PeqAudioSettingUtils.getInstance().initPeqData(mActivity);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        //todo 2023.6.5 需要兼容上一个市场版本的sharedPreference数据
        //List<PeqDataItemInfo> localDataItems = /*PeqDataManager.getInstance().*/loadPeqDataListFromLocal();
        //本地已有的所有列表数据
        //PeqDataManager.PeqDataItemInfo currentSelectedPeqDataItem = PeqDataManager.getInstance().getCurrentSelectedPeqDataItem(localDataItems);
        //todo 更新到UI
        //peqActivity.updateCurrentStyleName(currentSelectedPeqDataItem.name);
        SoundEffectConfig soundEffectConfig = SoundEffectManager.getInstance().getSelectedPEQSoundEffectConfig();
        String soundEffectConfigName = mActivity.getString(R.string.peq_mseb_none);
        PluginDataManager.PeqData peqData = null;
        if (soundEffectConfig != null) {
            if (BuildConfig.DEBUG) LogPlus.d("###soundEffectConfig id:" + soundEffectConfig.getId());
            if (soundEffectConfig.getId() != null) {
                peqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_PEQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.PeqData>() {
                });
                soundEffectConfigName = soundEffectConfig.getName();
                if (PluginDataManager.NONE_ID.equals(soundEffectConfig.getId())) {
                    soundEffectConfigName = mActivity.getString(R.string.peq_mseb_none);
                }
            }
        }

        //当前选中项的所有bands数据
        if (peqData == null) {
            peqData = PluginDataManager.getInstance().newNonePeqData();
        }

        peqActivity.updateCurrentStyleName(soundEffectConfigName);
        peqActivity.updateBands(peqData);
    }

    public List<SoundEffectConfig> getCachedSystems() {
        List<SoundEffectConfig> soundEffectConfigList = SoundEffectManager.getInstance().getCachedSystemPrefabs("peq");
        if (soundEffectConfigList == null) {
            return new ArrayList<>();
        }
        return soundEffectConfigList;
    }

    public static class PeqInfo {
        private String url;
        private String name;
        private String showName;
        private String describes;

        public String getShowName() {
            return showName;
        }

        public void setShowName(String showName) {
            this.showName = showName;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDescribes() {
            return describes;
        }

        public void setDescribes(String describes) {
            this.describes = describes;
        }

        @Override
        public String toString() {
            return "PeqInfo{" +
                    "url='" + url + '\'' +
                    ", name='" + name + '\'' +
                    ", describes='" + describes + '\'' +
                    '}';
        }
    }

    private void downloadPeqData(PeqInfo peqInfo) {
//        getRetrofit().create(PeqApiInterface.class).downloadFile(peqInfo.getUrl())
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<ResponseBody>() {
//                    @Override
//                    public void onSubscribe(@NonNull Disposable disposable) {
//
//                    }
//
//                    @Override
//                    public void onNext(@NonNull ResponseBody responseBody) {
//                        try {
//                            String json = responseBody.string();
//                            PluginDataManager.PluginData peqData = PluginDataManager.getInstance().jsonToData(json, PluginDataManager.PluginData.class);
//                            importDataToLocal(peqData, json, peqInfo.getShowName());
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    @Override
//                    public void onError(@NonNull Throwable throwable) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });

    }

    /*public Observable<ResponseBody> downloadPeqData(String peqDataUrl) {
        return getRetrofit().create(PeqApiInterface.class).downloadFile(peqDataUrl);
    }*/

    private void importDataToLocal(PluginDataManager.PluginData peqData, String peqDataJson, String show_name) {
//        for (PeqDataManager.PeqPluginDataItemInfo data : localDataAdapter.getDatas()) {
//            if (data.name.equals(show_name)) {
//                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.existing));
//                return;
//            }
//        }
//        resetAllChecked(localDataAdapter.getDatas(), false);
//        PeqDataManager.PeqPluginDataItemInfo peqDataItemInfo = new PeqDataManager.PeqPluginDataItemInfo();
//        peqDataItemInfo.setName(show_name);
//        //if (currentSelectedPeqDataItem != null) currentSelectedPeqDataItem.ischecked = false;
//        peqDataItemInfo.ischecked = true;
//        //currentSelectedPeqDataItem = peqDataItemInfo;
//        localDataAdapter.getDatas().add(1, peqDataItemInfo);
//        localDataAdapter.notifyDataSetChanged();
//        //保存列表
//        PeqDataManager.getInstance().savePeqDatasToLocal(localDataAdapter.getDatas());
//        //todo 更新到UI
//        peqActivity.updateBands(peqData);
//        peqActivity.updateCurrentStyleName(show_name);
//        //当前peq数据
//        PeqDataManager.getInstance().savePeqData(show_name, peqDataJson);
//        ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_config_import_success));
    }

    public void getDataFromServer() {
//        getRetrofit().create(PeqApiInterface.class).getDataList(getCurrentLanguage(), Build.MODEL.replaceAll(" ", ""), "PEQ")
//                .subscribeOn(Schedulers.io())
//                .map(responseBody -> {
//                    String string = responseBody.string();
//                    if (BuildConfig.DEBUG) {
//                        System.out.println("###peqonlineData:" + string);
//                    }
//                    OnlinePeqData onlinePeqData = PluginDataManager.getInstance().jsonToData(string, OnlinePeqData.class);
//                    if (onlinePeqData == null) {
//                        LogPlus.d("onlinePeqData is null");
//                        return new ArrayList<PeqInfo>();
//                    }
//                    return onlinePeqData.result;
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<List<PeqInfo>>() {
//                    @Override
//                    public void onSubscribe(@NonNull Disposable disposable) {
//
//                    }
//
//                    @Override
//                    public void onNext(@NonNull List<PeqInfo> msebInfos) {
//                        onlineDataAdapter.getDatas().clear();
//                        onlineDataAdapter.getDatas().addAll(msebInfos);
//                        onlineDataAdapter.notifyDataSetChanged();
//                    }
//
//                    @Override
//                    public void onError(@NonNull Throwable throwable) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });
    }

    public List<PeqInfo> getSystemPrefabs() throws Exception {
//        Response<ResponseBody> response = getRetrofit().create(PeqApiInterface.class).getDataListByCall(getCurrentLanguage(), Build.MODEL.replaceAll(" ", ""), "PEQ").execute();
//        if (response.body() == null)
//            return new ArrayList<>();
//        String string = response.body().string();
//        OnlinePeqData onlinePeqData = PluginDataManager.getInstance().jsonToData(string, OnlinePeqData.class);
//        if (onlinePeqData == null) {
//            LogPlus.d("onlinePeqData is null");
//            return new ArrayList<>();
//        }
//        return onlinePeqData.result;
        return new ArrayList<>();
    }

    public List<SoundEffectConfig> getConfigsOnServer() throws Exception {
        if (UserManager.getInstance().currentActiveUser() == null) {
            return null;
        }
        boolean isNetworkAvailable = NetWorkUtils.isConnected(mActivity.getApplicationContext());
        if (!isNetworkAvailable) {//网络不可用则暂不提交
            return null;
        }
        List<SoundEffectConfig> configOnServerDataList = new ArrayList<>();

        final CountDownLatch countDownLatch = new CountDownLatch(1);
//        UserManager.getInstance().getPluginConfigs(UserManager.getInstance().currentActiveUser().email(), "peq", UserManager.getInstance().currentActiveUser().token()).call(new Callback<String>() {
//            @Override
//            public void onSuccess(String data) {
//                if (BuildConfig.DEBUG) LogPlus.d("onSuccess: " + data);
//                ServerConfigList serverConfigList = null;
//                try {
//                    serverConfigList = PluginDataManager.getInstance().jsonToData(data, ServerConfigList.class);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                if (serverConfigList != null && serverConfigList.getList() != null) {
//                    configOnServerDataList.clear();
//                    for (ServerConfigList.DataList dataList : serverConfigList.getList()) {
//                        if (dataList.getList() != null) {
//                            for (ServerConfigList.DataList.ListDTO configItem : dataList.getList()) {
//                                SoundEffectConfig config = new SoundEffectConfig(configItem.getId() + ""/*服务端的id*/, configItem.getTitle(), false);
//                                config.setServerConfig(true);
//                                config.setConfigData(configItem.getConfigInfo());
//                                config.setServerConfigData(configItem);
//                                if (BuildConfig.DEBUG) LogPlus.d("###configData:" + config.getConfigData());
//                                configOnServerDataList.add(config);
//                            }
//                        }
//                    }
//                }
//
//                HibyUser hibyUser = UserManager.getInstance().currentActiveUser();
//                ServerConfigManager.getInstance().cacheConfigs(hibyUser, "peq", serverConfigList);
//                countDownLatch.countDown();
//            }
//
//            @Override
//            public void onError(Throwable t) {
//                t.printStackTrace();
//            }
//        });

        try {
            countDownLatch.await(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return configOnServerDataList;
    }

    private static class OnlinePeqData {
        public List<PeqInfo> result;
    }

    public String getCurrentLanguage() {
        Resources res = mActivity.getResources();
        Configuration config = res.getConfiguration();
        String country = config.locale.getCountry();
        return config.locale.getLanguage() + "-" + country;
    }

    //private Retrofit retrofit;

//    private Retrofit getRetrofit() {
//        if (retrofit != null) return retrofit;
//        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(s -> {
//            if (/*com.hiby.music.smartplayer.utils.Util.isApkInDebug(mActivity)*/false)
//                Log.v("http request", "log: " + s);
//        });
//        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

//        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        OkHttpClient client = builder.addInterceptor(logging)
//                .connectTimeout(10, TimeUnit.SECONDS)
//                .readTimeout(10, TimeUnit.SECONDS)
//                .writeTimeout(10, TimeUnit.SECONDS)
//                .sslSocketFactory(SmartPlayer.getInstance().getSSLSocketFactory(), SmartPlayer.getInstance().getX509TrustManager())
//                .hostnameVerifier(new NullHostNameVerifier())
//                .retryOnConnectionFailure(true).build();
//        retrofit = new Retrofit.Builder()
//                .client(client)
//                .baseUrl(DebugConfig.otaServerUrl())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .addConverterFactory(GsonConverterFactory.create(InitUtil.getGsonMapper()))
//                .build();
//        return retrofit;
//    }

    @Override
    public void onTuningStyleClick() {
        showTuningStyleDialog();
    }

    @Override
    public void onImportExportClick() {
        showImport();
    }

    @Override
    public void onSaveMixerValueClick() {
        final List<String> itemsList = new ArrayList<>();
        itemsList.add(mActivity.getString(R.string.peq_export_to_local));
        itemsList.add(mActivity.getString(R.string.peq_export_to_qrcode));

        QrManager.getInstance().showExportDesDialog(itemsList, mActivity, from -> {
            if (mActivity.getString(R.string.peq_export_to_local).equals(from)) {//导出到本地文件
                showSavePeqFormDialog();
                return;
            }
            if (mActivity.getString(R.string.peq_export_to_qrcode).equals(from)) {//导出为二维码
                createQrcodeAndShow();
                return;
            }
            System.out.println("from:" + from);
        });
    }

    public void createQrcodeAndShow() {
        try {
            byte[] peqData = currentPeqDataToBytes("用户自定义name");
            android.graphics.Bitmap qrBitmap = QrManager.getInstance().createQrcodeByEncoder(Constant.QR_SCHEMA_V1_PEQ, peqData, 300, 300, BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.appicon2_foreground));
            ((PEQActivity) mActivity).showQrcode(qrBitmap);
        } catch (QrManager.BusinessException e) {
            e.printStackTrace();
            ToastTool.showToast(mActivity.getApplicationContext(), e.getLocalizedMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showSavePeqFormDialog() {
        /*boolean flag = ShareprefenceTool.getInstance().getBooleanShareprefence(PEQActivity.PEQ_ISOPEN, mActivity, false);
        if (!flag) {
            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getApplicationContext().getResources().getString(R.string.eq_disable));
            return;
        }*/
        PEQImportDialog peqImportDialog = new PEQImportDialog(mActivity);
        peqImportDialog.initSavaCustomMixerDialog();
        peqImportDialog.showDialog();
    }

    @Override
    public void setPEQEnable(boolean enable, float preamp, boolean enablePreamp) {
        /*float[] floatSet = new float[3];
        floatSet[0] = enable ? 1 : 0;//是否打开 enable
        floatSet[1] = preamp;//总增益的值
        floatSet[2] = enablePreamp ? 1 : 0;//总增益是否打开
        SmartAv.getInstance().native_setObjectAttr("peq_global_param_peq", floatSet);*/

        //SmartAv.getInstance().native_setPeqValue("enable", enable ? 1 : 0/*是否打开 1.打开 0:关闭*/);
        //SmartAv.getInstance().native_setPeqValue("preamp", preamp);
        //SmartAv.getInstance().native_setPeqValue("en_preamp", enable ? 1 : 0/*是否打开 1.打开 0:关闭*/);
        PeqAudioSettingUtils.getInstance().enablePeq(mActivity, enable, enablePreamp, preamp);
    }

    @Override
    public void setPeqValues(List<Band> bands, double preAmp) {
        for (Band band : bands) {
            if (BuildConfig.DEBUG) LogPlus.d("band index:" + band.index);
            setPeqValue(band, preAmp);
        }
    }

    private void showTuningStyleDialog() {
//        CommanDialog dialog = new CommanDialog(mActivity, R.style.MyDialogStyle, CommanDialog.STYLE_NOTITLE_NOBUTTON);
//        dialog.addView(R.layout.dialog_peq_data_layout);
//        dialog.setCanceledOnTouchOutside(true);
//        View contentView = dialog.getContentView();
//        Button local = contentView.findViewById(R.id.local);
//        Button online = contentView.findViewById(R.id.online);
//        TextView network_tips = contentView.findViewById(R.id.network_tips);
//        RecyclerView recyclerView = contentView.findViewById(R.id.mseb_style_listview);
//        local.setSelected(true);
//        local.setOnClickListener(v -> {
//            v.setSelected(true);
//            online.setSelected(false);
//            recyclerView.setAdapter(localDataAdapter);
//            getDataFromLocal();
//
//            SkinManager.get().setTextViewColor(local, R.color.skin_button_text);
//            SkinManager.get().setTextViewColor(online, R.color.skin_primary_text);
//        });
//        online.setOnClickListener(v -> {
//            v.setSelected(true);
//            local.setSelected(false);
//            recyclerView.setAdapter(onlineDataAdapter);
//            getDataFromServer();
//
//            SkinManager.get().setTextViewColor(local, R.color.skin_primary_text);
//            SkinManager.get().setTextViewColor(online, R.color.skin_button_text);
//        });
//
//        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
//        recyclerView.setLayoutManager(layoutManager);
//
//        if (localDataAdapter == null) {
//            localDataAdapter = new CommonAdapter<PluginDataManager.PluginDataItem>(mActivity, R.layout.mseb_data_layout_item, new ArrayList<>()) {
//                @Override
//                protected void convert(ViewHolder holder, PluginDataManager.PluginDataItem peqDataItemInfo, int position) {
//                    holder.setText(R.id.mseb_name, peqDataItemInfo.name);
//                    holder.setChecked(R.id.checkbox_item, peqDataItemInfo.ischecked);
//                    SkinManager.get().setCheckBoxLeftDrawable(holder.getView(R.id.checkbox_item), R.drawable.skin_selector_checkbox_style_1);
//                    holder.itemView.setOnClickListener(v -> {
//                        for (PluginDataManager.PluginDataItem p : getDatas()) {
//                            p.setIschecked(false);
//                        }
//                        peqDataItemInfo.setIschecked(true);
//                        notifyDataSetChanged();
//
//                        PeqDataManager.getInstance().savePeqDatasToLocal(getDatas());
//
//                        PluginDataManager.PluginData peqData;
//                        if (position != 0) {
//                            String peqDataJson = PluginDataManager.getInstance().readPeqData(peqDataItemInfo.name);
//                            peqData = new Gson().fromJson(peqDataJson, PeqDataManager.PeqData.class);
//                            if (peqData == null) {
//                                ToastTool.showToast(mActivity.getApplicationContext(), "peqData is null");
//                            }
//                        } else {
//                            peqData = PluginDataManager.getInstance().initDefaultPeqData();
//                        }
//                        //todo 更新到UI
//                        peqActivity.updateBands(peqData);
//                        peqActivity.updateCurrentStyleName(peqDataItemInfo.name);
//                    });
//                    if (position != 0) {
//                        holder.itemView.setOnLongClickListener(v -> {
//                            showDeleteDialog(position);
//                            return false;
//                        });
//                    }
//                }
//            };
//        }
//        if (onlineDataAdapter == null) {
//            onlineDataAdapter = new CommonAdapter<PeqDataManager.PeqInfo>(mActivity, R.layout.dialog_mseb_online_listview_item, new ArrayList<>()) {
//                @Override
//                protected void convert(ViewHolder holder, PeqDataManager.PeqInfo peqDataItemInfo, int position) {
//                    ImageView describ = holder.getView(R.id.describ);
//                    describ.setTag(position);
//                    holder.setText(R.id.text_item, peqDataItemInfo.getShowName());
//                    describ.setOnClickListener(v -> showDescrbeDialog(peqDataItemInfo));
//                    describ.setVisibility(TextUtils.isEmpty(peqDataItemInfo.getDescribes()) ? View.INVISIBLE : View.VISIBLE);
//                    holder.itemView.setOnClickListener(v -> {
//                        if (!NetWorkUtils.isConnected(mActivity.getApplicationContext())) {
//                            ToastTool.showToast(mActivity.getApplicationContext(), R.string.networkError);
//                            return;
//                        }
//                        downloadPeqData(peqDataItemInfo);
//                    });
//                }
//            };
//        }
//
//        local.performClick();
//        dialog.show();
//        Window window = dialog.getWindow();
//        WindowManager.LayoutParams attributes = window.getAttributes();
//        DisplayMetrics dm = new DisplayMetrics();
//        //获取屏幕信息
//        mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
//        attributes.width = (int) (dm.widthPixels * (0.85));
//        attributes.gravity = Gravity.CENTER;
//        window.setAttributes(attributes);
//
//        ///////////////////////适配无障碍操作/////////////////////////
//        TextView tvTitle = dialog.findViewById(R.id.tv_title);
//        if (tvTitle != null) {
//            tvTitle.setContentDescription(tvTitle.getText() + "," + NameString.getResoucesString(mActivity, R.string.cd_click_to_close_dialog));
//            tvTitle.setOnClickListener((v) -> {
//                dialog.dismiss();
//            });
//        }
//        ///////////////////////适配无障碍操作/////////////////////////
    }

    private void getDataFromLocal() {
//        localDataAdapter.getDatas().clear();
//        localDataAdapter.getDatas().addAll(PeqDataManager.getInstance().loadPeqDataListFromLocal());
//
//        PeqDataManager.PeqPluginDataItemInfo currentSelectedPeqDataItem = null;
//        for (PeqDataManager.PeqPluginDataItemInfo peqDataItemInfo : localDataAdapter.getDatas()) {
//            if (peqDataItemInfo.ischecked) {
//                currentSelectedPeqDataItem = peqDataItemInfo;
//                break;
//            }
//        }
//        if (currentSelectedPeqDataItem == null) {
//            for (PeqDataManager.PeqPluginDataItemInfo peqDataItemInfo : localDataAdapter.getDatas()) {
//                peqDataItemInfo.ischecked = false;
//            }
//            currentSelectedPeqDataItem = localDataAdapter.getDatas().get(0);
//            currentSelectedPeqDataItem.ischecked = true;
//        }
//        peqActivity.updateCurrentStyleName(currentSelectedPeqDataItem.name);
//        localDataAdapter.notifyDataSetChanged();
    }

    private CommonAdapter<PluginDataManager.PluginDataItem> localDataAdapter;
    private CommonAdapter<PeqInfo> onlineDataAdapter;

    private void showDeleteDialog(int position) {
//        CommanDialog mDialog = new CommanDialog(mActivity, R.style.MyDialogStyle, CommanDialog.STYLE_3_HASTITLE_HASTWOBUTTON);
//        mDialog.titleTextView.setText(R.string.warning);
//        TextView textView = new TextView(mActivity);
//        textView.setText(R.string.ensure_delete);
//        SkinManager.get().setTextViewColor(textView, R.color.skin_primary_text);
////        textView.setTextColor(mActivity.getResources().getColor(R.color.skin_primary_text));
//        textView.setPadding(Util.dip2px(mActivity, 20), 0, 0, 0);
//        mDialog.addView(textView);
//        mDialog.ok.setText(R.string.ensure);
//        mDialog.cancle.setText(R.string.cancle);
//        mDialog.ok.setOnClickListener(view -> {
//            //todo 删除
//            PluginDataManager.PluginDataItem targetDeletePeqDataItem = localDataAdapter.getDatas().get(position);
//            boolean targetDeletePeqDataItemIschecked = targetDeletePeqDataItem.ischecked;
//            final String targetName = targetDeletePeqDataItem.name;
//            localDataAdapter.getDatas().remove(position);
//            if (targetDeletePeqDataItemIschecked) {
//                PluginDataManager.PluginDataItem nonePeqDataItemInfo = localDataAdapter.getDatas().get(0);
//                nonePeqDataItemInfo.ischecked = true;
//                peqActivity.updateCurrentStyleName(nonePeqDataItemInfo.name);
//                peqActivity.updateBands(PluginDataManager.getInstance().initDefaultPeqData());
//            }
//            localDataAdapter.notifyDataSetChanged();
//            //保存列表数据
//            PeqDataManager.getInstance().savePeqDatasToLocal(localDataAdapter.getDatas());
//
//            mDialog.dismiss();
//        });
//        mDialog.cancle.setOnClickListener(view -> mDialog.dismiss());
//        mDialog.show();
    }

//    private void showDescrbeDialog(PeqDataManager.PeqInfo msebInfo) {
//        CommanDialog tipDialog = new CommanDialog(mActivity, R.style.MyDialogStyle, CommanDialog.STYLE_4_HASTITLE_ONEBUTTON);
//        tipDialog.setCanceledOnTouchOutside(true);
//        tipDialog.titleTextView.setText(msebInfo.getName());
//        tipDialog.addView(R.layout.textview_sc);
//        TextView pathText = tipDialog.getContentView().findViewById(R.id.text_view);
////        pathText.setTextColor(mActivity.getResources().getColor(R.color.skin_primary_text));
//        SkinManager.get().setTextViewColor(pathText, R.color.skin_primary_text);
//        pathText.setText(msebInfo.getDescribes());
//        tipDialog.show();
//        tipDialog.ok.setOnClickListener(v -> tipDialog.dismiss());
//    }

    public static final int REQUEST_IMAGE = 9;

    @Override
    public void showImport() {
        final List<String> itemsList = new ArrayList<>();
        itemsList.add(mActivity.getString(R.string.peq_import_from_local));
        if (Util.checkAppIsProductApp() && CameraUtil.hasCamera()) itemsList.add(mActivity.getString(R.string.peq_import_from_qrcode));
        itemsList.add(mActivity.getString(R.string.peq_import_from_album));

        QrManager.getInstance().showImportSourceDialog(itemsList, mActivity, from -> {
            if (mActivity.getString(R.string.peq_import_from_local).equals(from)) {//从本地文件导入
                showImportExportDialog();
                return;
            }
            if (mActivity.getString(R.string.peq_import_from_qrcode).equals(from)) {//从二维码导入
                QrManager.getInstance().startScan(mActivity, PEQActivity.REQUEST_QR_CODE);
                return;
            }
            if (mActivity.getString(R.string.peq_import_from_album).equals(from)) {//从相册导入
                android.content.Intent intent = new android.content.Intent();
                intent.setAction(android.content.Intent.ACTION_PICK);
                intent.setType("image/*");
                mActivity.startActivityForResult(intent, REQUEST_IMAGE);
                return;
            }
            System.out.println("from:" + from);
        });
    }

    @Override
    public void showAddDialog() {
        //showSavePeqFormDialog();
        //todo 弹出输入name弹框
//        CustomSoundEffectPersistDialog customSoundEffectPersistDialog = new CustomSoundEffectPersistDialog(mActivity, name -> {
//            peqActivity.updateCurrentStyleName(name);
//            String peqDataJson = getCurrentPeqData(name);
//            PeqDataManager.getInstance().savePeqData(name, peqDataJson);
//            PeqDataManager.PeqDataItemInfo peqDataItem = new PeqDataManager.PeqDataItemInfo();
//            peqDataItem.name = name;
//            PeqDataManager.getInstance().addPeqDataItem(peqDataItem);
//            //updateBands();
//            SoundEffectConfig soundEffectConfig = new SoundEffectConfig(name, name, false);
//            SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(soundEffectConfig);
//            //输入更多信息
//            showPluginEditFormDialog("peq", soundEffectConfig);
//        });
//        customSoundEffectPersistDialog.showDialog();

        showPluginEditFormDialog("peq", null, null, null);
    }

    @Override
    public void showEditDialog(SoundEffectConfig targetSoundEffectConfig) {
        showPluginEditFormDialog("peq", targetSoundEffectConfig, null, null);
    }

    @Override
    public Object importDataToLocal(SoundEffectConfig soundEffectConfig) {
        if (!soundEffectConfig.isSystem()) {
            //保存列表选中
            SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(soundEffectConfig);
            PluginDataManager.PeqData peqData = null;
            //todo 更新UI
            if (soundEffectConfig.isServerConfig()) {
                try {
                    java.util.Map<String, Object> data = PluginDataManager.getInstance().jsonToData(soundEffectConfig.getConfigData(), new TypeToken<java.util.Map<String, Object>>() {
                    });
                    peqData = new PluginDataManager.PeqData();
                    peqData.device = "";
                    peqData.description = "";
                    List<LinkedTreeMap> bands = (ArrayList<LinkedTreeMap>) data.get("bands");
                    peqData.bands = new ArrayList<>(bands.size());
                    for (LinkedTreeMap bandMap : bands) {
                        peqData.bands.add(new PluginDataManager.BandItem().setFreq((Double) bandMap.get("freq")).setQ((Double) bandMap.get("q")).setGain((Double) bandMap.get("gain")).setOn(((Double) bandMap.get("on")).intValue()).setFilter(((Double) bandMap.get("filter")).intValue()));
                    }
                    peqData.pre_amp = (double) data.get("pre_amp");

                    PluginDataManager.getInstance().savePluginData(PluginDataManager.KEY_PEQ, new PluginDataManager.PluginData(soundEffectConfig.getId(), soundEffectConfig.getName(), peqData));
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            } else {
                peqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_PEQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.PeqData>() {
                });
            }
            peqActivity.updateBands(peqData);
            peqActivity.updateCurrentStyleName(soundEffectConfig.getName());
            return null;
        }

        if (NetWorkUtils.isConnected(mActivity.getApplicationContext())) {
            //属于在线数据 需要下载
//            downloadPeqData(soundEffectConfig.getDataUrl())
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new Observer<ResponseBody>() {
//                        @Override
//                        public void onSubscribe(@NonNull Disposable disposable) {
//
//                        }
//
//                        @Override
//                        public void onNext(@NonNull ResponseBody responseBody) {
//                            try {
//                                String json = responseBody.string();
//                                PluginDataManager.PeqData peqData = PluginDataManager.getInstance().jsonToData(json, PluginDataManager.PeqData.class);
//                                String id = soundEffectConfig.getId();
//                                PluginDataManager.getInstance().savePluginData(PluginDataManager.KEY_PEQ, new PluginDataManager.PluginData(id, peqData.name, peqData));
//                                peqActivity.updateBands(peqData);
//                                peqActivity.updateCurrentStyleName(soundEffectConfig.getName());
//
//                                SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(new SoundEffectConfig(soundEffectConfig.getId(), soundEffectConfig.getName(), true));
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//
//                        @Override
//                        public void onError(@NonNull Throwable throwable) {
//                            //加载出错则尝试使用缓存的数据
//                            try {
//                                String json = soundEffectConfig.getSystemData();
//                                PluginDataManager.PeqData peqData = PluginDataManager.getInstance().jsonToData(json, PluginDataManager.PeqData.class);
//                                String id = soundEffectConfig.getId();
//                                PluginDataManager.getInstance().savePluginData(PluginDataManager.KEY_PEQ, new PluginDataManager.PluginData(id, peqData.name, peqData));
//                                peqActivity.updateBands(peqData);
//                                peqActivity.updateCurrentStyleName(soundEffectConfig.getName());
//
//                                SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(new SoundEffectConfig(soundEffectConfig.getId(), soundEffectConfig.getName(), true));
//                            } catch (Exception ex) {
//                                ex.printStackTrace();
//                            }
//                        }
//
//                        @Override
//                        public void onComplete() {
//
//                        }
//                    });
        } else {
            try {
                String json = soundEffectConfig.getSystemData();
                PluginDataManager.PeqData peqData = PluginDataManager.getInstance().jsonToData(json, PluginDataManager.PeqData.class);
                String id = soundEffectConfig.getId();
                PluginDataManager.getInstance().savePluginData(PluginDataManager.KEY_PEQ, new PluginDataManager.PluginData(id, peqData.name, peqData));
                peqActivity.updateBands(peqData);
                peqActivity.updateCurrentStyleName(soundEffectConfig.getName());

                SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(new SoundEffectConfig(soundEffectConfig.getId(), soundEffectConfig.getName(), true));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return null;
    }

    private void showImportExportDialog() {
        /*boolean flag = ShareprefenceTool.getInstance().getBooleanShareprefence(PEQActivity.PEQ_ISOPEN, mActivity.getApplicationContext(), false);
        if (!flag) {
            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getApplicationContext().getResources().getString(R.string.eq_disable));
            return;
        }*/
        PEQImportDialog eqImportDialog = new PEQImportDialog(mActivity);
        eqImportDialog.togetLocalFile(mActivity);
    }

    @Override
    public String storageCallback(String eqName) {
        LogPlus.d("eqName:" + eqName);
        return null;
    }

    @Override
    public String importCallback(String importEqName) {
        LogPlus.d("importEqName:" + importEqName);
        return null;
    }

    @Override
    public boolean newSettings(boolean flag, String settingsName) {
        //保存新设定
        LogPlus.d("settingsName:" + settingsName);
        if (TextUtils.isEmpty(settingsName)) {
            ToastTool.showToast(mActivity.getApplicationContext(), "empty");
            return false;
        }

        List<PluginDataManager.PluginDataItem> peqDataItemInfos = PluginDataManager.getInstance().getDataItemsFromLocal(PluginDataManager.KEY_PEQ);
        PluginDataManager.PluginDataItem targetPeqDataItemInfo = null;
        for (PluginDataManager.PluginDataItem peqDataItemInfo : peqDataItemInfos) {
            if (peqDataItemInfo.name.equals(settingsName)) {
                targetPeqDataItemInfo = peqDataItemInfo;
                break;
            }
        }
        if (targetPeqDataItemInfo != null) {
            //同名的配置已存在, 直接覆盖
            //ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.existing));
            targetPeqDataItemInfo.setPluginData(new PluginDataManager.PluginData(targetPeqDataItemInfo.getId(), targetPeqDataItemInfo.getName(), newPeqDataWithCurrent(settingsName, targetPeqDataItemInfo.getDevice(), targetPeqDataItemInfo.getDescription())));
            PluginDataManager.getInstance().saveDataItems(PluginDataManager.KEY_PEQ, peqDataItemInfos);
            peqActivity.updateCurrentStyleName(settingsName);
            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.peq_store_successful));
            return true;
        }
        //插入一条新的数据
        PluginDataManager.PluginDataItem peqItem = new PluginDataManager.PluginDataItem();
        peqItem.ischecked = true;
        peqItem.name = settingsName;
        peqItem.setPluginData(new PluginDataManager.PluginData(peqItem.getId(), peqItem.getName(), newPeqDataWithCurrent(settingsName, peqItem.getDevice(), peqItem.getDescription())));
        peqDataItemInfos.add(peqItem);
        PluginDataManager.getInstance().saveDataItems(PluginDataManager.KEY_PEQ, peqDataItemInfos);

        peqActivity.updateCurrentStyleName(settingsName);
        ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getResources().getString(R.string.peq_store_successful));
        return true;
    }

    @Override
    public void resetMixerSettings() {
        LogPlus.d("resetMixerSettings:");
    }

    @Override
    public boolean newMixerLocalSetting(String name, String localFilePath) {
        LogPlus.d("newMixerLocalSetting localFilePath:" + localFilePath);
        try {
            PluginDataManager.PeqData peqData = new PluginDataManager.PeqData();
            peqData.name = name;
            peqData.pre_amp = peqActivity.getPreAmp();
            peqData.bands = new ArrayList<>();
            for (Band band : peqActivity.getBands()) {
                PluginDataManager.BandItem bandItem = new PluginDataManager.BandItem();
                bandItem.filter = band.filterType;
                bandItem.freq = band.getFreq();
                bandItem.on = band.on ? 1 : 0;
                bandItem.gain = band.getGain();
                bandItem.q = band.getQ();
                peqData.bands.add(bandItem);
            }
            String json = PluginDataManager.getInstance().toJson(peqData);
            FileUtil.writeBytesToFile(json.getBytes(), localFilePath);
            File file = new File(localFilePath);
            return file.exists() && file.length() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void importDataToLocal(String data, File file) {
        PluginDataManager.PeqData peqData = null;

        try {
            peqData = PluginDataManager.getInstance().jsonToData(data, PluginDataManager.PeqData.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (peqData == null || peqData.name == null || peqData.bands == null) {
            //非json则尝试AutoEQ 的格式
            //todo 支持导入AutoEQ的格式
            /**
             * Preamp: -6.1 dB
             * Filter 1: ON LSC Fc 105 Hz Gain 0.5 dB Q 0.70
             * Filter 2: ON PK Fc 165 Hz Gain -2.9 dB Q 0.47
             * Filter 3: ON PK Fc 8537 Hz Gain 5.0 dB Q 1.18
             * Filter 4: ON PK Fc 3109 Hz Gain 6.5 dB Q 2.65
             * Filter 5: ON PK Fc 2012 Hz Gain -3.0 dB Q 1.99
             * Filter 6: ON HSC Fc 10000 Hz Gain -6.1 dB Q 0.70
             * Filter 7: ON PK Fc 5900 Hz Gain 3.1 dB Q 5.79
             * Filter 8: ON PK Fc 4936 Hz Gain -2.0 dB Q 6.00
             * Filter 9: ON PK Fc 39 Hz Gain -0.5 dB Q 2.46
             * Filter 10: ON PK Fc 70 Hz Gain 0.3 dB Q 2.52
             */
            try {
                peqData = parseAutoEQ(data, file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (peqData == null || peqData.name == null || peqData.bands == null) {
            //兼容处理旧版本数据
            OldPeqData oldPeqData;
            final Gson gson = new Gson();
            try {
                oldPeqData = gson.fromJson(data, OldPeqData.class);
                peqData = new PluginDataManager.PeqData();
                peqData.name = oldPeqData.name;
                peqData.device = "";
                peqData.description = "";
                peqData.pre_amp = oldPeqData.preamp;
                peqData.bands = new ArrayList<>();
                for (OldBandItem bandItem : oldPeqData.bands) {
                    peqData.bands.add(new PluginDataManager.BandItem().setGain(bandItem.gain).setFreq(bandItem.freq).setQ(bandItem.q).setOn(bandItem.on).setFilter(bandItem.filter));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            //兼容处理旧版本数据
        }
        if (peqData == null) {
            ToastTool.showToast(mActivity.getApplicationContext(), "data error");
            return;
        }
        importDataFromLocal(peqData);
    }

    /**
     * 从本地文件导入
     *
     * @param peqData
     */
    @Override
    public void importDataFromLocal(PluginDataManager.PeqData peqData) {

        /////////////同名的音效要在保存之前让用户选择，不能导入之后提醒用户。这样会导致用户自己的音效被覆盖/////////////
        if (PluginDataManager.getInstance().isExists(PluginDataManager.KEY_PEQ, peqData.name)) {
            SmartPlayerApplication.runOnUiThread(() -> {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_config_samename_exists));
                showPluginEditFormDialog("peq", null, peqData, dataItem -> {
                    //导入并启用
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_config_import_success));
                    peqActivity.updateCurrentStyleName(dataItem.name);
                    peqActivity.updateBands(peqData);
                });
            });
            return;
        }
        /////////////同名的音效要在保存之前让用户选择，不能导入之后提醒用户。这样会导致用户自己的音效被覆盖/////////////

        //新增
        PluginDataManager.PluginDataItem dataItem = new PluginDataManager.PluginDataItem();
        dataItem.setIschecked(true);
        dataItem.setName(peqData.name);
        if (TextUtils.isEmpty(dataItem.getName())) {
            dataItem.name = new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date());
        }
        dataItem.setDevice(peqData.device);
        dataItem.setDescription(peqData.description);
        dataItem.setPluginData(new PluginDataManager.PluginData(dataItem.getId(), dataItem.name, peqData));
        peqActivity.updateCurrentStyleName(dataItem.name);
        peqActivity.updateBands(peqData);
        PluginDataManager.getInstance().addDataItem(PluginDataManager.KEY_PEQ, dataItem);

        //todo 8.mseb从相册导入功能无效，扫码导入然后选择相册有效。 9.使用8中导入功能默认没有同步到服务器
        SoundEffectConfig soundEffectConfig = new SoundEffectConfig(dataItem.getId(), peqData.name, false);
        if (UserManager.getInstance().currentActiveUser() != null && NetWorkUtils.isConnected(mActivity)) {
            doSaveToServer("peq", soundEffectConfig, dataItem);
        }
        //todo 8.mseb从相册导入功能无效，扫码导入然后选择相册有效。 9.使用8中导入功能默认没有同步到服务器

        SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(soundEffectConfig);
        ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_config_import_success));
    }

    public interface PeqApiInterface {
//        @POST("/app/msebSetting/findMsebSettingList")
//        @FormUrlEncoded
//        Observable<ResponseBody> getDataList(@Field("languageCode") String languageCode,
//                                             @Field("productName") String productName,
//                                             @Field("type") String type);
//
//        @POST("/app/msebSetting/findMsebSettingList")
//        @FormUrlEncoded
//        Call<ResponseBody> getDataListByCall(@Field("languageCode") String languageCode,
//                                             @Field("productName") String productName,
//                                             @Field("type") String type
//        );
//
//
//        @GET
//        Observable<ResponseBody> downloadFile(@Url String url);
//
//        @GET
//        Call<ResponseBody> downloadFileByCall(@Url String url);
    }

    /**
     * 下发到媒体库
     *
     * @param band
     * @return
     */
    @Override
    public float[] setPeqValue(Band band, double preAmp) {
        if (band == null) return null;
//        float[] floatSet = new float[6];
//        floatSet[0] = band.index; //当前的点  index
//        floatSet[1] = band.on ? 1 : 0;// on
//        floatSet[2] = (float) band.getFreq();
//        floatSet[3] = (float) band.getQ();
//        floatSet[4] = (float) (band.getGain());//
//        floatSet[5] = band.filterType;// on model  0低架/1峰值/2高架
//        SmartAv.getInstance().native_setObjectAttr("peq_param_peq", floatSet);
        //if (BuildConfig.DEBUG) LogPlus.d("setValue to peq: " + Arrays.toString(floatSet));

        //SmartAv.getInstance().native_setPeqValue("index", band.index);
        //SmartAv.getInstance().native_setPeqValue("on", band.on ? 1 : 0);
        //SmartAv.getInstance().native_setPeqValue("freq", (float) band.getFreq());
        //SmartAv.getInstance().native_setPeqValue("Q", (float) band.getQ());
        //SmartAv.getInstance().native_setPeqValue("boost", (float) band.getGain());
        //SmartAv.getInstance().native_setPeqValue("mode", band.filterType);

        PeqAudioSettingUtils.getInstance().setPEQValues(mActivity, band, preAmp);

        return /*(float[]) SmartAv.getInstance().getObjectAttr("peq_response")*/null;
    }

    private double lastPreAmp;

    @Override
    public float[] setPeqPreAmp(double preAmp) {
        boolean isPreAmpChanged = Math.abs(lastPreAmp - preAmp) > 0.02;
        if (isPreAmpChanged) {
            lastPreAmp = preAmp;
            PeqAudioSettingUtils.getInstance().setPEQPreamp(mActivity, preAmp);
        }
        return null;
    }

    /**
     * 用户已修改则修改为"自定义"
     */
    @Override
    public void changeToNone() {
        peqActivity.updateCurrentStyleName(mActivity.getString(R.string.peq_mseb_none));
        SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(new SoundEffectConfig(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), false));
    }

    @Override
    public void onPause() {
        saveTempPeqData();
    }

    private void saveTempPeqData() {
        PluginDataManager.PeqData peqData = null;
        try {
            peqData = newPeqDataWithCurrent(mActivity.getString(R.string.peq_mseb_none), "", "");
            PeqAudioSettingUtils.getInstance().saveAllPeqData(mActivity, peqData);
        } catch (Throwable e) {
            e.printStackTrace();
        }

        SoundEffectConfig currentSelected = SoundEffectManager.getInstance().getSelectedPEQSoundEffectConfig();
        if (currentSelected == null) {
            return;
        }
        if (currentSelected.isSystem()) {
            return;
        }
        if (BuildConfig.DEBUG) LogPlus.d("###currentSelected.id:" + currentSelected.getId());

        if (PluginDataManager.NONE_ID.equals(currentSelected.getId())) {
            PluginDataManager.getInstance().savePluginData(PluginDataManager.KEY_PEQ, new PluginDataManager.PluginData(PluginDataManager.NONE_ID, mActivity.getString(R.string.peq_mseb_none), peqData));
        }
    }

    @Override
    public void onDestroy() {

    }

    @Override
    public void onQrcodeDecoded(String content) {
        //todo 解析二维码内容并导入数据
        if (!isValidPeqData(content)) {
            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_invalid_peq_data));
            return;
        }
        doParseAndImportPeqData(content);
    }

    private boolean isValidPeqData(String resultData) {
        return resultData != null && resultData.startsWith(Constant.QR_SCHEMA_PEQ);
    }

    private void doParseAndImportPeqData(String content) {
        PluginDataManager.PeqData peqData;
        try {
            peqData = (PluginDataManager.PeqData) QrManager.getInstance().decodeQrcodeByDecoder(content);
        } catch (QrManager.BusinessException e) {
            e.printStackTrace();
            ToastTool.showToast(mActivity.getApplicationContext(), e.getLocalizedMessage());
            return;
        } catch (Exception e) {
            e.printStackTrace();
            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_invalid_peq_data));
            return;
        }

        /////////////同名的音效要在保存之前让用户选择，不能导入之后提醒用户。这样会导致用户自己的音效被覆盖/////////////
        if (PluginDataManager.getInstance().isExists(PluginDataManager.KEY_PEQ, peqData.name)) {
            ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_config_samename_exists));
            showPluginEditFormDialog("peq", null, peqData, dataItem -> {
                //导入并启用
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_config_import_success));
                peqActivity.updateCurrentStyleName(dataItem.name);
            });
            return;
        }
        /////////////同名的音效要在保存之前让用户选择，不能导入之后提醒用户。这样会导致用户自己的音效被覆盖/////////////

        //导入
        importDataFromLocal(peqData);
    }

    public PluginDataManager.PeqData newPeqDataWithCurrent(String name, String device, String description) {
        PluginDataManager.PeqData peqData = new PluginDataManager.PeqData();
        peqData.name = name;
        peqData.device = device;
        peqData.description = description;
        peqData.pre_amp = peqActivity.getPreAmp();
        peqData.bands = new ArrayList<>();
        for (Band band : peqActivity.getBands()) {
            PluginDataManager.BandItem bandItem = new PluginDataManager.BandItem();
            bandItem.filter = band.filterType;
            bandItem.freq = band.getFreq();
            bandItem.on = band.on ? 1 : 0;
            bandItem.gain = band.getGain();
            bandItem.q = band.getQ();
            peqData.bands.add(bandItem);
        }
        return peqData;
    }


    private byte[] currentPeqDataToBytes(String name) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] nameBytes = name.getBytes();
        baos.write(ByteBuffer.allocate(4).putInt(nameBytes.length).array());
        baos.write(nameBytes);//name
        baos.write(ByteBuffer.allocate(4).putFloat((float) peqActivity.getPreAmp()).array());//preamp
        for (Band band : peqActivity.getBands()) {
            baos.write(band.filterType);//filter
            baos.write(ByteBuffer.allocate(4).putFloat((float) band.getFreq()).array());//freq
            baos.write(band.on ? 1 : 0);//on
            baos.write(ByteBuffer.allocate(4).putFloat((float) band.getGain()).array());//gain
            baos.write(ByteBuffer.allocate(4).putFloat((float) band.getQ()).array());//q
        }
        baos.close();
        return baos.toByteArray();
    }

    public PluginDataManager.PeqData getPeqData(SoundEffectConfig soundEffectConfig) throws Exception {
        PluginDataManager.PeqData peqData = null;
        if (!soundEffectConfig.isSystem() && !soundEffectConfig.isServerConfig()) {
            PluginDataManager.PeqData data = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_PEQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.PeqData>() {
            });
            if (data != null) {
                return data;
            }
        } else if (soundEffectConfig.isServerConfig()) {//从服务器端拉取的配置
            try {
                ServerConfigManager.ServerPeqDataConfig serverPeqDataConfig = PluginDataManager.getInstance().jsonToData(soundEffectConfig.getConfigData(), ServerConfigManager.ServerPeqDataConfig.class);

                peqData = new PluginDataManager.PeqData();
                peqData.bands = serverPeqDataConfig.getBands();
                peqData.pre_amp = serverPeqDataConfig.getPre_amp();
                peqData.name = soundEffectConfig.getName();
                peqData.device = soundEffectConfig.getServerConfigData().getDevice();
                peqData.description = soundEffectConfig.getServerConfigData().getDescription();
            } catch (Exception e) {
                e.printStackTrace();
                peqData = null;
            }
        } else {
            //todo
            //系统预设 属于在线数据 需要下载
            String json = soundEffectConfig.getSystemData();
            try {
                if (NetWorkUtils.isConnected(mActivity.getApplicationContext())) {
                    String url = soundEffectConfig.getDataUrl();
                    if (TextUtils.isEmpty(url)) {
                        url = soundEffectConfig.getId();
                    }
                    //Response<ResponseBody> response = getRetrofit().create(PeqApiInterface.class).downloadFileByCall(url).execute();
                    //json = response.body().string();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            peqData = PluginDataManager.getInstance().jsonToData(json, PluginDataManager.PeqData.class);
        }
        return peqData;
    }

    private PluginDataManager.PeqData parseAutoEQ(String data, File file) throws Exception {
        String[] textLines = data.split("\n");
        //Filter 1: ON LSC Fc 105 Hz Gain 0.5 dB Q 0.70
        final String filterRegex = "Filter\\s+(\\d{1,2}):\\s+(ON|OFF)\\s+(LSC|PK|HSC)\\s+Fc\\s+(\\d{1,5})\\s+Hz\\s+Gain\\s+(.+)\\s+dB\\s+Q\\s+(.+)";
        Pattern filterPattern = Pattern.compile(filterRegex);
        //Preamp: -6.1 dB
        final String preampRegex = "Preamp:\\s+(.+)\\s+dB";
        Pattern preampPattern = Pattern.compile(preampRegex);

        PluginDataManager.PeqData peqData = new PluginDataManager.PeqData();
        String name = file.getName();
        int extStartIndex = name.lastIndexOf(".");
        if (extStartIndex != -1 && !TextUtils.isEmpty(name)) {
            name = name.substring(0, extStartIndex);
        }
        peqData.name = name;
        peqData.device = "";
        peqData.description = "";
        peqData.bands = new ArrayList<>();
        for (String line : textLines) {
            Matcher matcher = filterPattern.matcher(line);
            if (matcher.find()) {
                final int expectedGroupCount = 6;
                if (matcher.groupCount() != expectedGroupCount) {
                    throw new Exception("autoEq 文件格式异常 filter需要格式为: Filter 1: ON LSC Fc 105 Hz Gain 0.5 dB Q 0.70");
                }
                String full = matcher.group(0);
                String bandNumber = matcher.group(1);//ignore 按读取顺序
                String bandOn = matcher.group(2);
                String filterType = matcher.group(3);
                String fc = matcher.group(4);
                String gain = matcher.group(5);
                String q = matcher.group(6);

                PluginDataManager.BandItem bandItem = new PluginDataManager.BandItem();
                bandItem.on = "ON".equals(bandOn) ? 1 : 0;
                bandItem.filter = "PK".equals(filterType) ? 1 : ("LSC".equals(filterType) ? 0 : ("HSC".equals(filterType) ? 2 : 0));
                bandItem.freq = Double.parseDouble(fc);
                bandItem.gain = Double.parseDouble(gain);
                bandItem.q = Double.parseDouble(q);
                peqData.bands.add(bandItem);
            } else {
                matcher = preampPattern.matcher(line);
                if (!matcher.find()) {
                    throw new Exception("autoEq 文件格式异常 只能有 Filter 及 Preamp");
                }
                final int expectedGroupCount = 1;
                if (matcher.groupCount() != expectedGroupCount) {
                    throw new Exception("autoEq 文件格式异常 preamp需要格式为: Preamp: -6.1 dB");
                }

                String full = matcher.group(0);
                String preamp = matcher.group(1);

                peqData.pre_amp = Double.parseDouble(preamp);
            }
        }

        return peqData;
    }

    private Dialog formDialog;

    public void showPluginEditFormDialog(String type, SoundEffectConfig targetSoundEffectConfig, PluginDataManager.PeqData peqData, PluginDataManager.OnSaveItemCallback onSaveItemCallback) {
        if (mActivity == null || mActivity.isFinishing() || mActivity.isDestroyed()) return;
        Context mContext = mActivity;
        if (formDialog != null && formDialog.isShowing()) {
            formDialog.dismiss();
        }
        formDialog = new Dialog(mContext, R.style.peqLogSendDialogStyle);
        formDialog.setCanceledOnTouchOutside(false);
        formDialog.setContentView(R.layout.peq_plugin_config_form_dialog);
        EditText etName = formDialog.findViewById(R.id.et_name);
        final boolean isToInsert = targetSoundEffectConfig == null;
        PluginDataManager.PluginDataItem targetPeqDataItem = null;
        if (!isToInsert) {
            etName.setText(targetSoundEffectConfig.getName());
            TextView tvFormTitle = formDialog.findViewById(R.id.tv_form_title);
            tvFormTitle.setText(mActivity.getString(R.string.peq_edit));

            targetPeqDataItem = PluginDataManager.getInstance().getDataItem(PluginDataManager.KEY_PEQ, targetSoundEffectConfig.getId());
        }
        EditText etHeadphone = formDialog.findViewById(R.id.et_headphone);
        EditText etDesc = formDialog.findViewById(R.id.et_desc);
        TextView tvDescTitle = formDialog.findViewById(R.id.tv_desc);
        final int maxDescLength = 50;
        tvDescTitle.setText(mActivity.getString(R.string.peq_plg_config_desc_title, (etDesc.getText().length() + "/" + maxDescLength)));
        etDesc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvDescTitle.setText(mActivity.getString(R.string.peq_plg_config_desc_title, (etDesc.getText().length() + "/" + maxDescLength)));
            }
        });

        if (targetPeqDataItem != null) {
            etHeadphone.setText(targetPeqDataItem.getDevice());
            etDesc.setText(targetPeqDataItem.getDescription());
        }
        if (peqData != null) {
            etName.setText(peqData.name);
            etHeadphone.setText(peqData.device);
            etDesc.setText(peqData.description);
        }
        CheckBox cbSaveToServer = formDialog.findViewById(R.id.cbSaveToServer);
        final String persistsKey = "soundConfigSaveToServer";
        final boolean isChecked = ShareprefenceTool.getInstance().getBooleanShareprefence(persistsKey, mActivity.getApplicationContext(), /*true*/false);
        cbSaveToServer.setChecked(isChecked);
        cbSaveToServer.setOnCheckedChangeListener((buttonView, isChecked1) -> ShareprefenceTool.getInstance().setBooleanSharedPreference(persistsKey, isChecked1, mActivity.getApplicationContext()));
        formDialog.findViewById(R.id.container_checkbox).setVisibility(View.GONE);
        formDialog.findViewById(R.id.container_checkbox).setOnClickListener(v -> cbSaveToServer.setChecked(!cbSaveToServer.isChecked()));
        Button btn_cancel = formDialog.findViewById(R.id.btn_cancel);
        Button btn_send = formDialog.findViewById(R.id.btn_send);
        formDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        SkinManager.get().changeCustomView(btn_cancel, true);
        SkinManager.get().changeCustomView(btn_send, true);
        SkinManager.get().setCheckBoxButton(cbSaveToServer, R.drawable.peq_skin_selector_checkbox_circle_3);
        btn_send.setOnClickListener(v -> {
            if (TextUtils.isEmpty(etName.getText())) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_name_required));
                return;
            }
            if (etName.getText().length() > 30) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_name_length_1_10));
                return;
            }
            if (false && TextUtils.isEmpty(etHeadphone.getText())) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_device_required));
                return;
            }
            if (false && TextUtils.isEmpty(etDesc.getText())) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_description_required));
                return;
            }
            if (etDesc.getText().length() > maxDescLength) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_description_required_0) + maxDescLength);
                return;
            }
            if (cbSaveToServer.isChecked()) {
                if (UserManager.getInstance().currentActiveUser() == null) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_net_notlogin_details));
                    return;
                }
                boolean isNetworkAvailable = NetWorkUtils.isConnected(mActivity.getApplicationContext());
                if (!isNetworkAvailable) {//网络不可用
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_error_no_network));
                    return;
                }
            }
            //todo
            String name = etName.getText().toString();
            String ear = etHeadphone.getText().toString();
            String desc = etDesc.getText().toString();

            SoundEffectConfig soundEffectConfig;
            PluginDataManager.PluginDataItem dataItem;

            PluginDataManager.PeqData targetPeqData = null;
            if (peqData != null) {
                targetPeqData = peqData;
            } else {
                targetPeqData = newPeqDataWithCurrent(name, ear, desc);
            }
            if (isToInsert) {
                ////////重新定义下：重名的音效不能保存。如果用户的音效已经有这个名字提示用户重新命名，不然不保存。////////
                if (PluginDataManager.getInstance().isExists(PluginDataManager.KEY_PEQ, name)) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_config_samename_exists));
                    return;
                }
                ////////重新定义下：重名的音效不能保存。如果用户的音效已经有这个名字提示用户重新命名，不然不保存。////////
                //todo 新增
                dataItem = new PluginDataManager.PluginDataItem();
                dataItem.setName(name);
                dataItem.setDevice(ear);
                dataItem.setDescription(desc);
                dataItem.setPluginData(new PluginDataManager.PluginData(dataItem.getId(), name, targetPeqData));
                PluginDataManager.getInstance().addDataItem(PluginDataManager.KEY_PEQ, dataItem);

                //updateBands();
                soundEffectConfig = new SoundEffectConfig(dataItem.getId(), name, false);
                SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(soundEffectConfig);

                peqActivity.updateCurrentStyleName(name);

                if (onSaveItemCallback != null) onSaveItemCallback.onSuccess(dataItem);
            } else {
                //todo 更新
                try {
                    //获取本地已存在的dataItem, 后续保存到服务器需要关联该 dataItem
                    dataItem = PluginDataManager.getInstance().getDataItem(PluginDataManager.KEY_PEQ, targetSoundEffectConfig.getId());
                    dataItem.setName(name);
                    dataItem.setDevice(ear);
                    dataItem.setDescription(desc);
                    dataItem.setPluginData(new PluginDataManager.PluginData(dataItem.getId(), name, targetPeqData));

                    boolean isUpdated = PluginDataManager.getInstance().updateDataItem(PluginDataManager.KEY_PEQ, dataItem);
                    if (!isUpdated) {
                        ToastTool.showToast(mActivity.getApplicationContext(), "update filed");
                        return;
                    }

                    soundEffectConfig = targetSoundEffectConfig;
                    soundEffectConfig.setName(name);
                    SoundEffectManager.getInstance().saveSoundEffectConfigAsPEQ(soundEffectConfig);

                    soundEffectConfig.setServerDataId(dataItem.getServerDataId());

                    peqActivity.updateCurrentStyleName(name);
                } catch (Exception e) {
                    ToastTool.showToast(mActivity, e.getLocalizedMessage());
                    return;
                }
            }
            ////////////////////////////////同步保存到服务器////////////////////////////////
            if (cbSaveToServer.isChecked()) {
                if (UserManager.getInstance().currentActiveUser() == null) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_net_notlogin_details));
                    return;
                }
                boolean isNetworkAvailable = NetWorkUtils.isConnected(mActivity.getApplicationContext());
                if (!isNetworkAvailable) {//网络不可用
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_error_no_network));
                    return;
                }
                doSaveToServer(type, soundEffectConfig, dataItem);
            }
            ////////////////////////////////同步保存到服务器////////////////////////////////

            formDialog.dismiss();
        });
        btn_cancel.setOnClickListener(v -> formDialog.dismiss());
        if (Util.checkAppIsProductR6()/*专业版设备*/ /*&& Build.VERSION.SDK_INT == Build.VERSION_CODES.Q*//*Android 9*/) {
            //////////////////////专业版设备 R6 Android 9系统无法显示弹框内容//////////////////
            SmartPlayerApplication.getMainHandler().postDelayed(() -> formDialog.show(), 300);
            //////////////////////专业版设备 R6 Android 9系统无法显示弹框内容//////////////////
        } else {
            formDialog.show();//专业版设备 R6 Android 9系统无法显示弹框内容
        }
    }

    public void showResetMixerSettings(Context context, OnResetConfirmCallback onResetConfirmCallback) {
        final CommanDialog dialog = new CommanDialog(context, R.style.peqMyDialogStyle, CommanDialog.STYLE_3_HASTITLE_HASTWOBUTTON);
        dialog.setCanceledOnTouchOutside(true);
        dialog.addView(R.layout.peq_dialog_content_delete_audio);
        dialog.titleTextView.setText(context
                .getString(R.string.peq_reset));

        View contentView = dialog.getContentView();
        TextView tv_content = contentView.findViewById(R.id.tv_dialog_content);//R.string.confirm_reset_current_settings)
        tv_content.setText(context.getText(R.string.peq_reset_current_settings));
        dialog.ok.setOnClickListener(v -> {
            if (onResetConfirmCallback != null) onResetConfirmCallback.onReset();
            dialog.dismiss();
        });
        dialog.cancle.setOnClickListener(v -> dialog.dismiss());
        dialog.show();
    }

    public interface OnResetConfirmCallback {
        void onReset();
    }

    private void doSaveToServer(String type, SoundEffectConfig soundEffectConfig, PluginDataManager.PluginDataItem dataItem) {
        boolean saveToServer = true;
        ////////////////////////////////同步保存到服务器////////////////////////////////
        if (saveToServer) {
            if (UserManager.getInstance().currentActiveUser() == null) {
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_plg_net_notlogin_details));
                return;
            }
            boolean isNetworkAvailable = NetWorkUtils.isConnected(mActivity.getApplicationContext());
            if (!isNetworkAvailable) {//网络不可用
                ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_error_no_network));
                return;
            }

            Object configs = ServerConfigManager.getInstance().getConfigs(type, soundEffectConfig.getName(), dataItem.getDevice(), "", dataItem.getDescription(), soundEffectConfig);

            final PluginDataManager.PluginDataItem sourceDataItem = dataItem;
            ServerConfigManager.getInstance().savePluginConfigToServer(type, configs, new Callback<String>() {
                @Override
                public void onSuccess(String resp) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_data_submission_successful));
                    //todo 记录服务器端id 与本地数据关联(标识是否已保存到服务器)
                    ServerConfigSave serverConfigSave = null;
                    try {
                        serverConfigSave = PluginDataManager.getInstance().jsonToData(resp, ServerConfigSave.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String serverRecordId = null;
                    if (serverConfigSave != null && serverConfigSave.getList() != null && !serverConfigSave.getList().isEmpty()) {
                        Long id = serverConfigSave.getList().get(0).getId();
                        if (id != null) {
                            serverRecordId = id + "";
                        }
                    }

                    sourceDataItem.setServerDataId(serverRecordId);

                    PluginDataManager.getInstance().saveDataItems(PluginDataManager.KEY_PEQ, PluginDataManager.getInstance().getDataItemsFromLocal(PluginDataManager.KEY_PEQ));
                }

                @Override
                public void onError(Throwable t) {
                    ToastTool.showToast(mActivity.getApplicationContext(), mActivity.getString(R.string.peq_data_submission_failed) + t.getLocalizedMessage());
                }
            });
        }
    }

    public List<SoundEffectConfig> getCachedConfigs() throws Exception {
        List<SoundEffectConfig> configOnServerDataList = new ArrayList<>();
        HibyUser hibyUser = UserManager.getInstance().currentActiveUser();
        if (null == hibyUser) {
            return configOnServerDataList;
        }
        ServerConfigList serverConfigList = ServerConfigManager.getInstance().getCachedConfigs(hibyUser, "peq");

        if (serverConfigList != null && serverConfigList.getList() != null) {
            for (ServerConfigList.DataList dataList : serverConfigList.getList()) {
                if (dataList.getList() != null) {
                    for (ServerConfigList.DataList.ListDTO configItem : dataList.getList()) {
                        SoundEffectConfig config = new SoundEffectConfig(configItem.getId() + ""/*服务端的id*/, configItem.getTitle(), false);
                        config.setServerConfig(true);
                        config.setConfigData(configItem.getConfigInfo());
                        config.setServerConfigData(configItem);
                        if (BuildConfig.DEBUG) LogPlus.d("###configData:" + config.getConfigData());
                        configOnServerDataList.add(config);
                    }
                }
            }
        }
        return configOnServerDataList;
    }

    private static class OldPeqData {
        @SerializedName("a")
        public List<OldBandItem> bands;
        @SerializedName("b")
        public String name;
        @SerializedName("c")
        public double preamp;
    }

    private static class OldBandItem {
        @SerializedName("a")
        public double freq;
        @SerializedName("b")
        public double q;
        @SerializedName("c")
        public double gain;
        @SerializedName("d")
        public int on;
        @SerializedName("e")
        public int filter;
    }
}
